<template>
  <div>
    <VxeTableVue
      ref="tableEl"
      module-name="客户"
      :queryFormData="state.formData"
      :column-config="columnConfig"
      data-list-api="/customer/page"
      :show-top-add-btn="false"
      :show-top-del-btn="false"
      :show-del-btn="false"
      :on-mounted-query="false"
      :show-action-column="hasPermi(['coustomer-maintain-user', 'coustomer-update-status'])"
      show-footer
      :footer-data="footerData"
    >
      <!------------------------------------------ 查询 ------------------------------------------------------->

      <template #queryItem>
        <el-form-item label="客户" prop="customerIds" class="mgr30">
          <SelectVue v-model="state.formData.customerIds" label="customerName" option-api="/customer/page" :query-params="{ current: 1, size: 99999 }" clearable style="width: 220px" />
        </el-form-item>
        <el-form-item label="客户状态" prop="customerStatus" class="mgr30">
          <SelectVue
            v-model="state.formData.customerStatus"
            :option-list="[
              { name: '归档', id: '0' },
              { name: '正常', id: '1' }
            ]"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="服务人员" prop="userIds" class="mgr30">
          <SelectVue v-model="state.formData.userIds" option-api="/customer/getBindUsers" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="创建时间" class="mgr30">
          <DatePickVue style="width: 240px" v-model:start-time="state.formData.params.startTime" v-model:end-time="state.formData.params.endTime" />
        </el-form-item>
      </template>

      <!------------------------------------------ 表格列 ------------------------------------------------------->

      <template #topExtra="{ selectedList }">
        <el-button v-has-permi="['coustomer-maintain-user']" type="primary" :disabled="!selectedList.length" @click="handleMaintainUser(selectedList, 'batch')">维护服务人员</el-button>
        <div>
          <span class="mgl20">已选</span>
          <span class="mgr5 mgl5" style="color: var(--el-color-primary)">{{ selectedList.length }}</span>
          <span>个</span>
        </div>
      </template>

      <template #customerStatus="{ row }: SlotCustomer">
        <el-tag :type="row.customerStatus === '0' ? 'danger' : 'success'">{{ row.customerStatus === '0' ? '归档' : '正常' }}</el-tag>
      </template>

      <template #agentIds="{ row }: SlotCustomer">
        <el-button type="primary" link @click="toPageAgentList(row)">{{ row.agentIds?.length ?? 0 }}</el-button>
      </template>
      <template #userList="{ row }: SlotCustomer">
        <div>{{ row.userList?.map(item => item.name).join(',') }}</div>
      </template>

      <template #extraBtn1="{ row }: SlotCustomer">
        <div class="flex">
          <el-button v-has-permi="['coustomer-maintain-user']" type="primary" link @click="handleMaintainUser([row], 'single')">维护服务人员</el-button>
          <el-button v-has-permi="['coustomer-update-status']" type="primary" link @click="handleStatus(row)">修改状态</el-button>
        </div>
      </template>
    </VxeTableVue>

    <!------------------------------------------ 维护人员弹窗 ------------------------------------------------------->

    <DialogVue ref="dialogEl" title="维护服务人员" :width="500" :form-data="state.maintainFormData" @before-submit="onBeforeSubmit">
      <SelectVue v-model="state.selectedUsers" :transfer="false" multiple option-api="/auth/role/getUserByRoleName" :query-params="{ roleName: '服务人员' }" />
    </DialogVue>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onActivated } from 'vue'
  import { type VxeTableViewInstance, VxeTableVue } from '@/components/table'
  import DialogVue, { type DialogVueInstance } from '@/components/dialog'
  import DatePickVue from '@/components/date-pick'
  import { columnConfig } from './config'
  import { Ui, hasPermi } from '@/utils'
  import request from '@/service'
  import SelectVue from '@/components/select'
  import type { SlotCustomer, ICustomer, IMaintainFormData } from './config'
  import router from '@/router'

  const tableEl = ref<VxeTableViewInstance>()
  const dialogEl = ref<DialogVueInstance>()

  const state = reactive({
    formData: {
      customerIds: '',
      customerStatus: '',
      userIds: '',
      params: {
        startTime: '',
        endTime: ''
      }
    },
    maintainFormData: {
      customerIds: [],
      userIds: []
    } as IMaintainFormData,
    selectedUsers: [] as string[]
  })

  /**----------------------------methods----------------------------------------------------------------------- */

  const footerData = computed(() => [{ checkbox: '合计', agentIds: tableEl.value?.dataList[0]?.count }])

  /**
   * 维护服务人员
   */
  const handleMaintainUser = (customers: ICustomer[], type: 'batch' | 'single') => {
    state.maintainFormData.customerIds = customers.map(item => item.id)
    state.selectedUsers = type === 'batch' ? [] : customers[0].userList.map(item => item.id)
    dialogEl.value?.handleOpen()
  }

  /**
   * 提交服务人员
   */
  const onBeforeSubmit = (data: IMaintainFormData, fn: any) => {
    fn(false)
    state.maintainFormData.userIds = state.selectedUsers

    const handleConfirm = () => {
      request.put('/customer/update', state.maintainFormData).then(res => {
        if (res.code !== 0) return Ui.useMessage('error', res.msg)
        dialogEl.value?.handleClose()
        reflesh()
      })
    }

    if (state.selectedUsers.length) return handleConfirm()

    Ui.useMessageBox({
      text: '未选择服务人员，保存后将把原有的服务人员移除，确定保存？”，点击确定后，将所选客户的服务人员清空',
      handleConfirm
    })
  }

  const toPageAgentList = (row: ICustomer) => {
    const { customerName, id } = row
    router.push({
      path: '/agent/list',
      query: {
        customerName,
        customerId: id
      }
    })
  }

  /**
   * 修改状态
   * @param row
   */
  const handleStatus = (customer: ICustomer) => {
    const handleConfirm = () => {
      customer.customerStatus = customer.customerStatus === '0' ? '1' : '0'
      request.put('/customer/updateStatus', customer).then(res => {
        if (res.code !== 0) return Ui.useMessage('error', res.msg)
        dialogEl.value?.handleClose()
        reflesh()
      })
    }

    Ui.useMessageBox({
      handleConfirm,
      text: `当前客户状态为“${customer.customerStatus === '1' ? '正常' : '归档'}”，修改后将同步把客户下的客户一起更新为“${customer.customerStatus === '0' ? '正常' : '归档'}”，确定修改？`
    })
  }

  const reflesh = () => {
    tableEl.value?.query()
  }

  /**----------------------------lifecycle----------------------------------------------------------------------- */
  onActivated(() => {
    const { startTime, endTime } = router.currentRoute.value.query
    state.formData.params.startTime = startTime as string
    state.formData.params.endTime = endTime as string

    reflesh()
  })
</script>

<style scoped></style>
